package com.txMsg.server.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.txMsg.server.config.TxMsgConfig;
import com.txMsg.server.dao.TxMsgMapper;
import com.txMsg.server.entity.TxMsg;
import com.txMsg.server.enums.DeleteFlagEnum;
import com.txMsg.server.enums.TxMsgStatusEnum;
import com.txMsg.server.service.TxMsgMQService;
import com.txMsg.server.service.TxMsgService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.Date;
import java.util.List;

@Service
@Slf4j
public  class TxMsgServiceImpl extends ServiceImpl<TxMsgMapper,TxMsg> implements TxMsgService {
    @Autowired
    TxMsgMQService txMsgMQService;
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private TxMsgConfig txMsgConfig;

    @Override
    public Object deleteTxMsg(String txMsgId) {
        TxMsg updateTxMsg = new TxMsg();
        updateTxMsg.setTxMsgId(txMsgId);
        UpdateWrapper<TxMsg> updateWrapper = new UpdateWrapper<>(updateTxMsg);
        //先逻辑删 后面改成物理删除
        TxMsg txMsg = new TxMsg();
        txMsg.setDeleteFlag(DeleteFlagEnum.DEL.getCode());
        txMsg.setUpdateTime(new Date());
        baseMapper.update(txMsg,updateWrapper);
        // baseMapper.delete(updateWrapper);
        return "成功";
    }

    @Override
    public void sendConfirmTxMsg() {
        QueryWrapper<TxMsg> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("delete_flag",DeleteFlagEnum.UN_DEL.getCode());
        queryWrapper.eq("status",TxMsgStatusEnum.CONFIRM.getCode());
        queryWrapper.lt("send_count",txMsgConfig.getMaxSendCount());
        IPage<TxMsg> page = new Page<TxMsg>();
        page.setSize(txMsgConfig.getSendConfirmTxMsgSize());
        baseMapper.selectPage(page,queryWrapper);
        ((TxMsgServiceImpl)AopContext.currentProxy()).listSendTxMsg(page.getRecords());
    }
    @Override
    public void callbackTxMsg() {
        QueryWrapper<TxMsg> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("delete_flag", DeleteFlagEnum.UN_DEL.getCode());
        queryWrapper.eq("status", TxMsgStatusEnum.PREPARE.getCode());
        DateTime dateTime = DateUtil.offsetMinute(new Date(),txMsgConfig.getCallbackTime()*-1);
        log.info("dateTime:{}",dateTime);
        queryWrapper.ge("create_time",dateTime);
        IPage<TxMsg> page = new Page<TxMsg>();
        page.setSize(txMsgConfig.getCallbackTxMsgSize());
        baseMapper.selectPage(page,queryWrapper);
        ((TxMsgServiceImpl)AopContext.currentProxy()).listCallbackTxMsg(page.getRecords());
    }

    @Override
    public boolean saveTxMsg(TxMsg txMsg) {
        txMsg.setCreateTime(new Date());
        return baseMapper.insert(txMsg) == 1;
    }

    @Override
    public boolean confirmTxMsg(String txMsgId) {
        TxMsg updateTxMsg = new TxMsg();
        updateTxMsg.setTxMsgId(txMsgId);
        Wrapper<TxMsg> updateWrapper = new QueryWrapper<>(updateTxMsg);
        List<TxMsg> listTxMsg = baseMapper.selectList(updateWrapper);
        ((TxMsgServiceImpl)AopContext.currentProxy()).listSendTxMsg(listTxMsg);
        return true;
    }
    @Override
    public void listSendTxMsg(List<TxMsg> listTxMsg){
        if(listTxMsg!=null&&listTxMsg.size()>0){
            Date now = new Date();
            listTxMsg.stream().forEach(txMsg->{

                txMsg.setUpdateTime(now);
                txMsg.setSendCount(txMsg.getSendCount()+1);
                baseMapper.updateById(txMsg);
                txMsgMQService.sendMsg(txMsg);
            });
        }
    }
    public void listCallbackTxMsg(List<TxMsg> listTxMsg){
        if(listTxMsg!=null&&listTxMsg.size()>0){
            Date now = new Date();
            listTxMsg.stream().forEach(txMsg->{
                txMsg.getCallbackServer();
                String url = txMsg.getCallbackServer() + txMsg.getCallbackApi();
                MultiValueMap<String,Object> map = new LinkedMultiValueMap<>();
                map.add("txMsgId",txMsg.getTxMsgId());
                map.add("callbackParam",txMsg.getCallbackParam());
                HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
                HttpEntity<MultiValueMap<String, Object>> request = new HttpEntity<>(map, headers);
                String data =restTemplate.postForObject(url,request,String.class);
//                txMsg.setUpdateTime(now);
//                txMsg.setSendCount(txMsg.getSendCount()+1);
//                baseMapper.updateById(txMsg);
                log.info(data);

            });
        }
    }

}
